package com.jiashihui.schema_lgorithm.java.thread.consumer;

import java.util.Queue;

/**
 * @ClassName Consumer
 * @Author Administrator
 * @Date 2019/04/08 21:58
 * @Version 1.0
 **/
public class Consumer extends Thread {
    private final Queue sharedQ;

    public Consumer(Queue sharedQ) {
        super("Consumer");
        this.sharedQ = sharedQ;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (sharedQ) {
                while (sharedQ.size() == 0) {
                    try {
                        System.out.println("Queue is empty, waiting");
                        sharedQ.wait();
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
                int number = (int) sharedQ.poll();
                System.out.println("consuming : " + number);
                sharedQ.notify();
                if (number == 3) {
                    break;
                }
            }
        }
    }
}
